package com.ms.service.module.datacenterlite;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import com.ms.service.error.ErrorCode;
import com.xpec.c4.db.dao.PlayerKeepSeatDAO;
import com.xpec.c4.db.model.PlayerKeepSeatModel;
import com.xpec.c4.game.time.TimeSys;

public class GameSuperCancelKeepDataAyncCommand extends CentralAsyncCommand {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1773409040309304782L;

	public CancelKeepDataOption option;

	@SuppressWarnings("unchecked")
	@Override
	public void asyncExecute() throws Exception {
		ConcurrentHashMap<String, GameKeepSeatAllData> keep = DataCenterLiteModule.getKeepSeat();
		for (Entry<String, GameKeepSeatAllData> entry : keep.entrySet()) {
			GameKeepSeatAllData allData = entry.getValue();

			// 同步鎖
			synchronized (allData) {
				ArrayList<GameKeepSeatData> list = allData.getDataList();
				boolean hasChange = false;
				Iterator<GameKeepSeatData> iterator = list.iterator();
				while (iterator.hasNext()) {
					GameKeepSeatData dd = iterator.next();
					if (dd.getGameName().equals(option.game) && dd.getHalltype().equals(option.halltype)
							&& dd.getSeatid().equals(option.seatid) && dd.getMachineid() == option.machineid) {
						iterator.remove();
						hasChange = true;
					}
				}

				if (!hasChange) {
					continue;
				}

				String guid = entry.getKey();
				PlayerKeepSeatModel model = PlayerKeepSeatDAO.getKeepSeatByGuid(guid);

				// 回存資料庫
				JSONArray keeplist = new JSONArray();
				for (GameKeepSeatData dd : list) {
					JSONObject obj = dd.toJson();
					keeplist.add(obj);
				}

				JSONObject db = new JSONObject();
				db.put("keep", keeplist);

				model.setContent(db.toJSONString());
				model.setModifytime(TimeSys.currentTimeMills());

				boolean result = PlayerKeepSeatDAO.modifyKeepSeatData(model);
				if (result != true) {
					errorCode = ErrorCode.UPDATE_KEEPDATA_ERR;
					return;
				}
			} // synchronized(allData)
		}
	}

	@Override
	public void callBackExecute(Object... userData) throws Exception {
		switch (option.methodType) {
		}
	}
}
